package Chapter05.Fruite;

import java.util.ArrayList;
import java.util.List;

public class Market {
    private List<Farmer> farmers = new ArrayList<Farmer>();
    private List<User> users = new ArrayList<User>();

    public void registerFarmer(String username, String password) {
        Farmer farmer = new Farmer(username, password);
        farmers.add(farmer);
        System.out.println("Farmer registered successfully.");
    }

    public void registerUser(String username, String password) {
        User user = new User(username, password);
        users.add(user);
        System.out.println("User registered successfully.");
    }

    public Farmer loginFarmer(String username, String password) {
        for (Farmer farmer : farmers) {
            if (farmer.getUsername().equals(username) && farmer.getPassword().equals(password)) {
                System.out.println("Farmer logged in successfully.");
                return farmer;
            }
        }
        System.out.println("Invalid username or password.");
        return null;
    }

    public User loginUser(String username, String password) {
        for (User user : users) {
            if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                System.out.println("User logged in successfully.");
                return user;
            }
        }
        System.out.println("Invalid username or password.");
        return null;
    }

    public void addFruit(Farmer farmer, String name, double price) {
        Fruit fruit = new Fruit(name, price);
        farmer.addFruit(fruit);
        System.out.println("Fruit added successfully.");
    }

    public List<Fruit> searchFruit(String name) {
        List<Fruit> result = new ArrayList<Fruit>();
        for (Farmer farmer : farmers) {
            for (Fruit fruit : farmer.getFruits()) {
                if (fruit.getName().equals(name)) {
                    result.add(fruit);
                }
            }
        }
        return result;
    }

    public void checkout(User user) {
        double total = 0;
        for (Fruit fruit : user.getCart()) {
                total += fruit.getPrice();
            }
            System.out.println("Total price: " + total);
            user.getCart().clear();
        }
}

